package com.financing.wap.weixin.handle.event;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.financing.wap.service.IDstIntegralRuleService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.CommonConstantUtil.CommonStatus;
import com.financing.wap.dto.DstMemberInfoDTO;
import com.financing.wap.dto.DstUserInfoDTO;
import com.financing.wap.service.ICommonService;
import com.financing.wap.service.IDstMemberInfoService;
import com.financing.wap.service.IDstUserInfoService;
import com.financing.wap.service.weixin.service.WeixinService;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.EmojiFilterUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.ArticleInfoVO;
import com.financing.wap.weixin.handle.CreatePosterHandler;
import com.financing.wap.weixin.handle.EventHandler;
import com.financing.wap.weixin.resp.Article;
import com.financing.wap.weixin.resp.NewsMessage;
import com.financing.wap.weixin.resp.TextMessage;
import com.financing.wap.weixin.util.MessageUtil;

/**
 * 扫描带参数二维码事件-用户未关注时，进行关注后的事件推送
 * @author lisu
 *
 */
@Service("subscribeEvent")
public class SubscribeEvent implements EventHandler{
	
	public static final  Object b = new Object();
	
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IDstUserInfoService dstUserInfoService;
	
    @Autowired
    private WeixinService weixinJincsServiceImpl;
	
	@Autowired
	private CreatePosterHandler createPosterHandler;
	
    @Autowired
    private IDstMemberInfoService dstMemberInfoService;
	
	@Autowired
	private ICommonService commonService;

	@Autowired
	private IDstIntegralRuleService dstIntegralRuleService;
	@Override
	public String messageHandler(Map<String, String> requestMap)
			throws Exception {

		String fromUserName = requestMap.get("FromUserName"); // 发送方帐号（open_id）
		String toUserName = requestMap.get("ToUserName");// 公众帐号
		
		String eventKey=requestMap.get("EventKey");
		
		boolean isRegister = true;// 是否注册
		
		logger.info("requestMap："+requestMap.toString());
		
		//关注  查询访问最后一条记录  
		ArticleInfoVO visitArticleInfo = commonService.visitArticleInfoGetFisrt(fromUserName);
		logger.info("eventKey:"+eventKey);
		synchronized (b) {
			// 新增用户
			// 用户是否存在
			DstUserInfoDTO wxUserInfo = new DstUserInfoDTO();
			wxUserInfo.setUserWechatOpenid(fromUserName);
			List<DstUserInfoDTO> queryList = dstUserInfoService
					.queryList(wxUserInfo);
			
			String userId = null;
			if (queryList == null || queryList.size() <= 0) {
				isRegister = false;
				// 根据openid获取用户信息
				WxMpUser mpUser = weixinJincsServiceImpl.getUserInfoForUserService(fromUserName);
				DstUserInfoDTO userInfo = new DstUserInfoDTO();
				userInfo.setUserWechatOpenid(mpUser.getOpenId());
				userInfo.setUserName(EmojiFilterUtil.filterEmoji(mpUser.getNickname()));
				userInfo.setUserWechatImage(mpUser.getHeadImgUrl());
				userInfo.setUserWechatAddress(mpUser.getProvince()+mpUser.getCity());
				userInfo.setUserSex(mpUser.getSex());
				userInfo.setFlagConcern(CommonConstantUtil.UserInfoStatus.FLAG_CONCERN_IS);// 已关注
				userInfo.setDeleteTag(CommonConstantUtil.CommonStatus.DELETE_TAG_NORMAL);// 否删除
				userInfo.setCreateDate(new Date(System.currentTimeMillis()));
				userInfo.setUpdateDate(new Date(System.currentTimeMillis()));
				userInfo.setRegisterDate(DateUtil.getString(
						userInfo.getCreateDate(), "yyyy-MM-dd"));
				userInfo.setCreateBy("system");
				userInfo.setUpdateBy("system");
				if (StringUtils.isNotBlank(userInfo.getUserWechatOpenid())) {
					if(StringUtils.isNotBlank(eventKey)&&eventKey.split("_").length>1){
						String userParentOpenId = eventKey.substring(eventKey.indexOf("_")+1);
						userInfo.setUserParentOpenId(userParentOpenId);
					}else{
//						if(visitArticleInfo!=null&&!StringUtil.isNullOrEmptyStr(visitArticleInfo.getUserOpenid())){
//							userInfo.setUserParentOpenId(visitArticleInfo.getUserOpenid());
//						}
					}
					// 新增用户
					dstUserInfoService.insert(userInfo);
					userId = userInfo.getId().toString();
					requestMap.put("userId", userId);

				}
			}  else {
				DstUserInfoDTO updateBean = queryList.get(0);
//				if(visitArticleInfo!=null&&!StringUtil.isNullOrEmptyStr(visitArticleInfo.getUserOpenid())
//						&&StringUtil.isNullOrEmptyStr(updateBean.getUserParentOpenId())){
//					updateBean.setUserParentOpenId(visitArticleInfo.getUserOpenid());
//				}
				if(StringUtil.isNullOrEmptyStr(updateBean.getUserParentOpenId())&&StringUtils.isNotBlank(eventKey)&&eventKey.split("_").length>1){
					String userParentOpenId = eventKey.substring(eventKey.indexOf("_")+1);
					updateBean.setUserParentOpenId(userParentOpenId);
				}
				updateBean
						.setFlagConcern(CommonConstantUtil.UserInfoStatus.FLAG_CONCERN_IS);// 再次关注
				updateBean.setUpdateDate(new Date(System.currentTimeMillis()));
				dstUserInfoService.update(updateBean);
				requestMap.put("userId", userId);
			}
			
			DstMemberInfoDTO dstMemberInfo=new DstMemberInfoDTO();
			dstMemberInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			dstMemberInfo.setUserOpenid(fromUserName);
			DstMemberInfoDTO member = dstMemberInfoService.queryListGetFirst(dstMemberInfo);
			if(member.getId()==null){
				dstMemberInfoService.createMember(fromUserName);
			}

			//关注 会员规则事件
			dstIntegralRuleService.executeSubscribe(fromUserName);
			logger.info("messageHandler isRegister:" + isRegister);
		}
		
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);
		
		// 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
//		String content="欢迎使用【麒麟展业】\n便捷操作轻松分享，转发爆文高效获客\n------------立即完善<a href='%s'>个人名片</a>\n目前您可免费体验VIP会员所有功能\n3秒创建一篇你的文章，点击<a href='%s'>【创建文章】</a>查看操作详情";
//		content=String.format(content, CommonStatus.settingPage,CommonStatus.articleCreatePage);
		//20190612 会员版本
		String content="\ue41f\ue41f\ue41f欢迎使用【麒麟展业】获客推广工具\n\n麒麟展业为您提供了以下服务：\n\ue00e海量10万+阅读量的文章\n\ue00e分享文章后访客实时通知\n\ue00e一键添加名片\n\ue00e随心插入广告到文章\n\n点击\ue231<a href='%s'>【获客方式】->【获客文章】</a>分享您的文章开始获客吧";
		content=String.format(content, CommonStatus.articlePage);
		if(!isRegister)
			content+="\n\n首次关注的会员体验大礼包已近为您备好,您可以点击\ue231<a href='"+CommonStatus.rulePage+"'>【会员中心】</a>了解更多";
		textMessage.setContent(content);
		logger.info("messageHandler allend!!!");
		String result= MessageUtil.textMessageToXml(textMessage);

		if(visitArticleInfo!=null){
			// 创建图文消息
			 NewsMessage newsMessage = new NewsMessage();
			 newsMessage.setToUserName(fromUserName);
			 newsMessage.setFromUserName(toUserName);
			 newsMessage.setCreateTime(new Date().getTime());
			 newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
			 newsMessage.setFuncFlag(0);
			 newsMessage.setArticleCount(1);
			 List<Article> articles=new ArrayList<Article>();
			String articleUrl=MessageFormat.format(CommonStatus.articleDetailPage, visitArticleInfo.getDstArticleCode(),"");
			//用户绑定文章地址
			Article e=new Article();
			e.setTitle(visitArticleInfo.getTitle());
			e.setPicUrl(visitArticleInfo.getThumbnail());
			e.setDescription(visitArticleInfo.getDescription());
			e.setUrl(articleUrl);
			articles.add(e);
			newsMessage.setArticles(articles);
			
			WxMpKefuMessage message = WxMpKefuMessage.TEXT()
				     .toUser(fromUserName)
				     .content(content)
				     .build();
			weixinJincsServiceImpl.sendKefuMessage(message);
			
			return MessageUtil.newsMessageToXml(newsMessage);
		}	
		return result;
	}

	@Override
	public void messageSubsequentHandler(Map<String, String> requestMap) throws Exception {
		
		Thread.sleep(1000);
		
		 // 发送方帐号（open_id）  
        String fromUserName = requestMap.get("FromUserName"); 
        String userId = requestMap.get("userId");
        String token = requestMap.get("token");
        
		
		logger.info("messageSubsequentHandler  allend!!!");
		
	}

}

